import React from 'react'
import { Text, View, RefreshControl, TouchableOpacity, FlatList, Image } from 'react-native'
import { Metrics, Colors, Fonts } from '../../Themes'
import { API, WINDOW } from '../../Services'
import styles from '../Styles/CommonContainerStyles'
import ListViewSeparator from '../../Components/ListViewSeparator'
import HomeProductCell from './HomeProductCell'

export default class ProductListCateScreen extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            dataSource: [],
            isRefreshing: false,
            gparent_id: props.gparent.cataCode,
        }
    }

    componentDidMount() {
        this._onRefresh()
    }

    _onRefresh = () => {
        this.setState({ isRefreshing: true })
        this._fetch_selectShopList()
    }

    //产品列表 
    _fetch_selectShopList() {
        const { gparent_id } = this.state
        let num = 10
        if (gparent_id == '') {
            num = 20
        }
        API.goodsByCataCode(gparent_id,num).then((response) => {
            const { ok, data } = response
            if (typeof (data) == 'object') {
                if (ok) {
                    this.setState({ dataSource: data.goodsListByCata, isRefreshing: false })
                } else {
                    WINDOW.showToastError(data.msg || '请求失败！')
                    this.setState({ isRefreshing: false })
                }
            } else {
                this._fetch_selectShopList()
            }
        })
    }

    _renderRow({ item }) {
        return (
            <TouchableOpacity onPress={() => this.props.navigation.navigate('ProductDetail', { item })}>
                <HomeProductCell {...item} />
            </TouchableOpacity>
        )
    }

    _ListEmptyComponent = () => {
        return (
            <View style={{ alignItems: 'center', justifyContent: 'center', alignSelf: 'center', marginTop: 100 }}>
                <Image source={require('../../Images/zanwudingdan.png')} />
                <Text style={{ fontSize: 16, color: '#666666', marginTop: 20 }}>暂无数据!</Text>
            </View>
        )
    }

    render() {
        return (
            <View style={[styles.container, { backgroundColor: Colors.background }]}>
                <FlatList
                    data={this.state.dataSource}
                    ListHeaderComponent={this._renderHeader}
                    ListEmptyComponent={this._ListEmptyComponent}
                    numColumns={2}
                    renderItem={this._renderRow.bind(this)}
                    keyExtractor={(item) => `${item.ID}-${item.goodsName}`}
                    onEndReachedThreshold={0.1}
                    refreshControl={<RefreshControl
                        onRefresh={this._onRefresh.bind(this)}
                        refreshing={this.state.isRefreshing} />} />
            </View>
        )
    }
}

